package service

import (
	"errors"
	"fmt"
	"gin_server/pkg/email"
	"gin_server/pkg/redis"
	"gin_server/pkg/utils"
)

type EmailService interface {
	// SendVerificationCode 发送邮箱验证码
	SendVerificationCode(emailAddr string) error

	// VerifyCode 验证邮箱验证码
	VerifyCode(emailAddr, code string) (bool, error)
}

// emailService 是EmailService接口的实现
type emailService struct{}

// NewEmailService 创建EmailService实例
func NewEmailService() EmailService {
	return &emailService{}
}

// SendVerificationCode 发送邮箱验证码
func (s *emailService) SendVerificationCode(emailAddr string) error {
	// 生成6位验证码
	code := utils.GenerateRandomCode(6)

	// 存储验证码到Redis，有效期10分钟
	codeKey := fmt.Sprintf("email_code:%s", emailAddr)
	err := redis.SetWithExpire(codeKey, code, 10)
	if err != nil {
		return errors.New("验证码存储失败")
	}

	// 发送验证码邮件
	err = email.SendVerificationCode(emailAddr, code)
	if err != nil {
		// 发送失败时删除存储的验证码
		redis.Delete(codeKey)
		return errors.New("验证码发送失败")
	}

	return nil
}

// VerifyCode 验证邮箱验证码
func (s *emailService) VerifyCode(emailAddr, code string) (bool, error) {
	// 从Redis获取验证码
	codeKey := fmt.Sprintf("email_code:%s", emailAddr)
	storedCode, err := redis.GetString(codeKey)
	if err != nil {
		return false, errors.New("验证码不存在或已过期")
	}

	// 验证验证码
	if storedCode != code {
		return false, errors.New("验证码错误")
	}

	// 验证成功后删除验证码（防止重复使用）
	redis.Delete(codeKey)

	return true, nil
}
